package com.rds.benchmark.operator;

import com.rds.benchmark.util.MakeValue;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.commands.JedisCommands;

import java.io.IOException;

public class StringOperator extends TypeOperatorBase {

    private Object conn;

    private String key;

    private String mode;

    private final String value = MakeValue.value;

    @Override
    public void init(Object conn, String key, int idx, String mode) {
        this.conn = conn;
        this.key = key;
        this.mode = mode;
    }

    @Override
    public Long clear() {
        return ((JedisCommands) conn).del(key);
    }

    @Override
    public void operate() throws IOException {
        if (conn instanceof JedisCommands) {
            JedisCommands jedis = (JedisCommands) conn;
            if (mode != null && mode.equals("req")) {
                jedis.set(key, value);
                times += 1;
            } else {
                jedis.set(key, value);
                String msg = jedis.get(key);
                if (!value.equals(msg)) {
                    times += 2;
                    throw new IOException("set value = '" + value + "', but get value = '" + msg + "'");
                } else {
                    jedis.del(key);
                    times += 3;
                }
            }
        }
    }
}
